import {
  Text,
  View,
  StyleSheet,
  Image,
  TouchableOpacity,
  Alert,
  ScrollView,
} from "react-native";
import PageContainer from "@/components/PageContainer";
import React, { useState, useRef } from "react";
import { useRouter, useFocusEffect } from "expo-router";
import { LinearGradient } from "expo-linear-gradient";
import { useTranslation } from "react-i18next";
import { queryAssetsFnAPi } from "../api/maret";
import { ToastAPI } from "@/components/Toast";

export default function Cart() {
  const router = useRouter();
  const { t } = useTranslation();
  const [cardsList, setCardsList] = useState<any[]>([]);
  const [price, setPrice] = useState({
    referencePriceAsDollar: 0,
    referencePriceAsCny: 0,
  });
  // 使用 useRef 来标记是否已经初始化加载过数据
  const isInitialized = useRef(false);

  const getCurrencyList = async () => {
    ToastAPI.loading(t("common.loading"), "center", -1);
     try {
      const res: any = await queryAssetsFnAPi();
          ToastAPI.close();
          if (res.code === 0) {
            setCardsList(res.result?.cards || []);
            setPrice({
              referencePriceAsDollar: res.result?.referencePriceAsDollar,
              referencePriceAsCny: res.result?.referencePriceAsCny,
            });
          } else {
            ToastAPI.error(
              res?.errMsg || t("common.loadFailed")
            );
          }
        } catch (error) {
          ToastAPI.close();
          // 捕获错误并关闭加载提示
          ToastAPI.error(JSON.stringify(error) || t("common.loadFailed"));
        }
  };

  useFocusEffect(() => {
    if (!isInitialized.current) {
      // 首次加载数据
      getCurrencyList();
      isInitialized.current = true;
    }
  });

  return (
    <PageContainer>
      <View className="bg-[#000] flex-1 p-[13px]">
        <View className="items-center flex-row h-[46px]">
          <Text className="w-[18px]"></Text>
          <View className="flex-1 flex-row justify-center">
            <Text className="text-[#fff] text-[18px]">
              {t("cast.my_assets")}
            </Text>
          </View>
          <Text className="w-[18px]"></Text>
        </View>
        <ScrollView
          showsVerticalScrollIndicator={false}
          showsHorizontalScrollIndicator={false}
        >
          <LinearGradient
            colors={["#62C5FE", "#A7DDFD"]}
            start={{ x: 0, y: 0 }}
            end={{ x: 0, y: 1 }}
            style={styles.topHeider}
          >
            <Text className="text-[22px] font-[600]">
              {price.referencePriceAsDollar}USDT
            </Text>
            <Text className="text-[14px]">
              ≈{price.referencePriceAsCny} CNY
            </Text>
            <Text className="text-[18px] font-[600] mt-[20px]">
              {t("cast.my_assets")}
            </Text>
            <Image
              source={require("@/assets/images/zici.png")}
              className="w-[145px] h-[102px] absolute top-[12px] right-[12px]"
            />
          </LinearGradient>
          <View className="mt-[22px] flex-row justify-between justify-center items-center">
            <View className="flex-1  flex-row justify-center">
              <TouchableOpacity
                onPress={() => {
                  isInitialized.current = false;
                  router.push("/recharge");
                }}
              >
                <View>
                  <Image
                    source={require("@/assets/images/zicancz.png")}
                    className="w-[53px] h-[53px]"
                  />
                  <Text className="text-[#fff] text-[14px] text-center mt-[10px]">
                    {t("cast.recharge")}
                  </Text>
                </View>
              </TouchableOpacity>
            </View>
            <View className="flex-1 flex-row justify-center">
              <TouchableOpacity
                onPress={() => {
                  isInitialized.current = false;
                  router.push("/recharge/WithdrawalCurrency");
                }}
              >
                <View>
                  <Image
                    source={require("@/assets/images/zicaitixian.png")}
                    className="w-[53px] h-[53px]"
                  />
                  <Text className="text-[#fff] text-[14px] text-center mt-[10px]">
                    {t("cast.withdrawal")}
                  </Text>
                </View>
              </TouchableOpacity>
            </View>
          </View>
          <View>
            {cardsList.map((item, index) => (
              <View
                className="bg-[#1E1E20] rounded-[15px] p-[12px] mt-[13px]"
                key={index}
              >
                <View className="flex-row items-center ">
                  <View className="flex-row gap-[10px] items-center">
                    <Image
                      source={{ uri: item?.logo }}
                      className="w-[30px] h-[30px] rounded-full"
                    />
                    <Text className="text-[#fff] text-[18px]">
                      {item?.symbol}
                    </Text>
                  </View>
                </View>
                <View className="mt-[15px] flex-row items-center justify-center">
                  <View className="flex-1">
                    <View>
                      <View>
                        <Text className="text-[#fff] text-[16px] text-center">
                          {item?.amount || 0}
                        </Text>
                      </View>
                      <View>
                        <Text className="text-[#fff] text-[16px] text-center"></Text>
                      </View>
                    </View>
                    <Text className="text-[#949494] text-[14px] mt-[10px] text-center">
                      {t("cast.quantity")}
                    </Text>
                  </View>
                  <View className="flex-1">
                    <View>
                      <View>
                        <Text className="text-[#fff] text-[16px] text-center">
                          {item?.referencePriceAsDollar || 0}
                        </Text>
                      </View>
                      <View>
                        <Text className="text-[#fff] text-[16px] text-center">
                          USDT
                        </Text>
                      </View>
                    </View>

                    <Text className="text-[#949494] text-[14px] mt-[10px] text-center">
                      {t("cast.price")}
                    </Text>
                  </View>
                  <View className="flex-1">
                    <View>
                      <View>
                        <Text className="text-[#fff] text-[16px] text-center">
                          {item?.referencePriceAsCny || 0}
                        </Text>
                      </View>
                      <View>
                        <Text className="text-[#fff] text-[16px] text-center">
                          CYN
                        </Text>
                      </View>
                    </View>
                    <Text className="text-[#949494] text-[14px] mt-[10px] text-center">
                      {t("cast.valuation")}
                    </Text>
                  </View>
                </View>
                <View
                  className="mt-[15px] py-[16px] px-[16px] flex-row justify-between items-center"
                  style={{
                    borderTopWidth: 1,
                    borderTopColor: "#303030",
                  }}
                >
                  <TouchableOpacity
                    className="flex-1 flex-row justify-center items-center gap-[5px]"
                    onPress={() => {
                      isInitialized.current = false;
                      router.push({
                        pathname: "/recharge",
                        params: {
                          assetId: item?.assetId,
                          symbol: item?.symbol,
                        },
                      });
                    }}
                  >
                    <View
                      className="flex-1 flex-row justify-center items-center gap-[5px]"
                      style={{
                        borderRightWidth: 1,
                        borderRightColor: "#303030",
                      }}
                    >
                      <Image
                        source={require("@/assets/images/cz.png")}
                        className="w-[22px] h-[18px]"
                      />
                      <Text className="text-[#fff] text-[16px]">
                        {t("cast.recharge_action")}
                      </Text>
                    </View>
                  </TouchableOpacity>
                  <TouchableOpacity
                    className="flex-1 flex-row justify-center items-center gap-[5px]"
                    onPress={() => {
                      isInitialized.current = false;
                      router.push({
                        pathname: "/recharge/WithdrawalCurrency",
                        params: {
                          assetId: item?.assetId,
                          symbol: item?.symbol,
                        },
                      });
                    }}
                  >
                    <View className="flex-1 flex-row justify-center items-center gap-[5px]">
                      <Image
                        source={require("@/assets/images/tx.png")}
                        className="w-[22px] h-[18px]"
                      />
                      <Text className="text-[#fff] text-[16px]">
                        {t("cast.withdrawal_action")}
                      </Text>
                    </View>
                  </TouchableOpacity>
                </View>
              </View>
            ))}
          </View>
        </ScrollView>
      </View>
    </PageContainer>
  );
}
const styles = StyleSheet.create({
  topHeider: {
    height: 130,
    marginTop: 22,
    borderRadius: 15,
    position: "relative",
    padding: 12,
    flexDirection: "column",
    justifyContent: "center",
  },
});
